//
//  UIControl+ADUtil.m
//  ADKit
//
//  Created by duzexu on 2017/12/11.
//

#import "UIControl+ADUtil.h"
#import "ADKitHeaders.h"

@interface UIControl ()

@property (nonatomic,assign) NSTimeInterval ad_acceptEventTime;

@end

@implementation UIControl (ADUtil)

static char AD_UIControl_AcceptEventInterval;
static char AD_UIControl_AcceptEventTime;

- (NSTimeInterval)ad_acceptEventInterval {
    return [[self getAssociatedValueForKey:&AD_UIControl_AcceptEventInterval] doubleValue];
}

- (void)setAd_acceptEventInterval:(NSTimeInterval)ad_acceptEventInterval {
    [self setAssociateValue:@(ad_acceptEventInterval) withKey:&AD_UIControl_AcceptEventInterval];
}

- (NSTimeInterval)ad_acceptEventTime {
    return [[self getAssociatedValueForKey:&AD_UIControl_AcceptEventTime] doubleValue];
}

- (void)setAd_acceptEventTime:(NSTimeInterval)ad_acceptEventTime {
    [self setAssociateValue:@(ad_acceptEventTime) withKey:&AD_UIControl_AcceptEventTime];
}

+ (void)load {
    [self swizzleInstanceMethod:@selector(sendAction:to:forEvent:) with:@selector(_ad_sendAction:to:forEvent:)];
}

- (void)_ad_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if (NSDate.date.timeIntervalSince1970 - self.ad_acceptEventTime < self.ad_acceptEventInterval) return;
    
    if (self.ad_acceptEventInterval > 0) {
        self.ad_acceptEventTime = NSDate.date.timeIntervalSince1970;
    }
    
    [self _ad_sendAction:action to:target forEvent:event];
}

@end
